package com.sgj.controller;

import com.sgj.entity.User;
import com.sgj.service.UserService;
import com.sgj.utils.VerifyCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author 沈国纪
 * @date 2021/12/10 20:25
 */
@Slf4j
@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;

	@Autowired
	private RedisTemplate redisTemplate;

	/**
	 * 登录
	 * @param username
	 * @param password
	 * @return
	 */
	@RequestMapping("/login")
	public String login(String username, String password, String code) {
		// 验证码对比
		String code1 = (String) redisTemplate.opsForValue().get("code");
		try {
			if (code1.equalsIgnoreCase(code)) {
				// 获取主体对象
				Subject subject = SecurityUtils.getSubject();

					subject.login(new UsernamePasswordToken(username, password));
					return "redirect:/index.jsp";
			} else {
				throw new RuntimeException("验证码错误");
			}
		} catch (UnknownAccountException e) {
			log.error("[UserController][login] 用户名错误");
		} catch (IncorrectCredentialsException e) {
			log.error("[UserController][login] 密码错误");
		} catch (RuntimeException e) {
			log.error("[UserController][login] 验证码错误");
		}
		return "redirect:/login.jsp";
	}

	/**
	 * 注册用户
	 * @param user
	 * @return
	 */
	@RequestMapping("/register")
	public String register(User user) {
		try {
			userService.register(user);
			return "redirect:/login.jsp";
		} catch (Exception e) {
			e.printStackTrace();
			log.error("注册失败");
			return "redirect:/register.jsp";
		}
	}

	@RequestMapping("/getImage")
	public void getImage(HttpServletResponse response) throws IOException {
		// 生成验证码
		String code = VerifyCodeUtils.generateVerifyCode(4);
		// 将验证码放入 redis,验证码 5 分钟内有效
		redisTemplate.opsForValue().set("code", code, 5, TimeUnit.MINUTES);
		// 将验证码存入图片
		ServletOutputStream os = response.getOutputStream();
		response.setContentType("image/png");
		VerifyCodeUtils.outputImage(220, 60, os, code);
	}

	/**
	 * 退出登录
	 * @return
	 */
	@RequestMapping("/logout")
	public String logout() {
		Subject subject = SecurityUtils.getSubject();
		// 退出登录
		subject.logout();
		return "redirect:/login.jsp";
	}
}